package cn.conac.rc.gateway.modules.ofs.rest;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cn.conac.rc.framework.utils.RestClientException;
import cn.conac.rc.framework.utils.ResultPojo;
import cn.conac.rc.gateway.modules.ofs.common.common;
import cn.conac.rc.gateway.modules.ofs.contsant.Contsants;
import cn.conac.rc.gateway.modules.ofs.entity.OrgOpinionsEntity;
import cn.conac.rc.gateway.modules.ofs.entity.OrgStatusEntity;
import cn.conac.rc.gateway.modules.ofs.entity.OrganizationEntity;
import cn.conac.rc.gateway.modules.ofs.service.OrgOpinionsService;
import cn.conac.rc.gateway.modules.ofs.service.OrgStatusService;
import cn.conac.rc.gateway.modules.ofs.service.OrganizationBaseService;
import cn.conac.rc.gateway.modules.ofs.service.OrganizationService;
import cn.conac.rc.gateway.security.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping(value="ofs/")
@Api(tags="部门的状态信息", description="三定信息")
public class OrgStatusController {

    @Autowired
    OrgStatusService  orgStatusService;
    
    @Autowired
    OrganizationService  organizationService;
    
    @Autowired
    OrganizationBaseService organizationBaseService;
    
	@Autowired
	OrgOpinionsService orgOpinionsService;
    
    @ApiOperation(value = "通过baseID获取状态信息", httpMethod = "GET", response = JSONObject.class, notes = "通过baseID获取状态信息")
    @RequestMapping(value = "bases/{id}/statuses", method = RequestMethod.GET)
    public JSONObject findStatusById(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "id", required = true) @PathVariable("id") Integer id)
            throws RestClientException, Exception {
        return orgStatusService.findById(id);
    }

	
    @ApiOperation(value = "提交审核", httpMethod = "POST", response = JSONObject.class, notes = "提交审核")
    @RequestMapping(value = "statuses/{baseId}/submit", method = RequestMethod.POST)
    public Object cudStatusUpdate(HttpServletRequest request, HttpServletResponse response,
    		@ApiParam("部门基本信息Id") @PathVariable("baseId") Integer baseId)
            throws RestClientException, Exception {
    	
    	 int orgSaveFlag = 0;
    	 ResultPojo resultInfo = new ResultPojo();
    	 if(null == baseId) {
    		  // 参数baseId为null场合
	       	  resultInfo.setCode(ResultPojo.CODE_FAILURE);
	          resultInfo.setMsg("[ baseId of parameter is null ] in function of statusUpdate " + ResultPojo.MSG_FAILURE);
	       	  resultInfo.setResult(null);
	       	  return resultInfo;
    	 }
    	 
    	 Map<String,String> idMap = new HashMap<String, String>();
    	
    	 //******************第一步从页面侧获取部门编制信息和部门状态实体对象***********
         // 根据baseId获得部门状态信息
    	 JSONObject orgStatusInfoJson =   orgStatusService.findById(baseId);
 		
    	 if(null == orgStatusInfoJson.getJSONObject("result")) {
    		 // 参数baseId为null场合
	       	  resultInfo.setCode(ResultPojo.CODE_FAILURE);
	          resultInfo.setMsg("[ result(orgStatusService.findById) is null ] in function of statusUpdate " + ResultPojo.MSG_FAILURE);
	       	  resultInfo.setResult(null);
	       	  return resultInfo;
    	 }
    	 
    	 OrgStatusEntity  statusEntityInfo = JSONObject.toJavaObject(orgStatusInfoJson.getJSONObject("result"), OrgStatusEntity.class);
         
    	 //*******************第二步保存部门的状态表******************************************
    	  // 设置更新用户ID
    	 statusEntityInfo.setUpdateUserId(UserUtils.getCurrentUser().getId());
    	 // 历史沿革场合
    	 if(Contsants.OFS_ORG_STATUS_IS_HISTORY_TRUE.equals(statusEntityInfo.getIsHistory())){
    		 // 设置通过（03）状态
        	 statusEntityInfo.setStatus(Contsants.OFS_AUDIT_THROUGH);
    	 } else {
    		 if(UserUtils.isBianBan()) {
    			// 设置通过（03）状态
            	 statusEntityInfo.setStatus(Contsants.OFS_AUDIT_THROUGH);
            	 orgSaveFlag =1;
    		 } else {
    			 // 设置待审核（01）状态
    	    	 statusEntityInfo.setStatus(Contsants.OFS_STATUS_PRE_AUDIT);
    		 }
    	 }
		  // 执行保存部门的状态表
		  JSONObject statusInfoJson = orgStatusService.saveOrUpdate(statusEntityInfo);
		 
		  // 判断保存是否成功失败
		  if (ResultPojo.CODE_SUCCESS.equals(statusInfoJson.getString("code")) ) {
			  // 保存成功场合
			  resultInfo.setCode(ResultPojo.CODE_SUCCESS);
			  resultInfo.setMsg(ResultPojo.MSG_SUCCESS);
			  idMap.put("baseId", statusInfoJson.getJSONObject("result").getString("id"));
			  resultInfo.setResult(idMap);
		  } else {
			 // 保存失败场合
			  resultInfo.setCode(statusInfoJson.getString("code"));
			  resultInfo.setMsg("[orgStatusService.saveOrUpdate] in function of empUpdate " 
					  						+ ResultPojo.MSG_FAILURE + "【"   + statusInfoJson.getString("msg") + "】");
			  resultInfo.setResult(null);
			  return  resultInfo;
		  }
    	 
		  if(orgSaveFlag == 1) {
			 String orgId = null;
			 // 将baseID同步更新到部门库主表中
			 // 根据baseID取得部门库ID（主表ID）
			JSONObject   baseInfoJson =  organizationBaseService.findById(baseId);
			if (ResultPojo.CODE_SUCCESS.equals(baseInfoJson.getString("code")) ) {
				orgId = baseInfoJson.getJSONObject("result").getString("orgId");
			} else {
				// 部门基本信息取得失败场合
				resultInfo.setCode(baseInfoJson.getString("code"));
				resultInfo.setMsg("[organizationBaseService.findById] in function of statusUpdate " + ResultPojo.MSG_FAILURE + "【"  + baseInfoJson.getString("msg") + "】" );
				resultInfo.setResult(null);
				return  resultInfo;
			}
			
			OrganizationEntity orgEntity = new OrganizationEntity();
			 // 根据orgID取得部门库详细信息
			JSONObject orgInfoJson =  organizationService.findById(orgId);
			
			if (ResultPojo.CODE_SUCCESS.equals(orgInfoJson.getString("code")) ) {
				orgEntity = JSONObject.toJavaObject(orgInfoJson.getJSONObject("result"), OrganizationEntity.class);
				// 部门库信息取得成功场合
				orgEntity.setBaseId(baseId.toString());
				// **********************************审核通过时点将部门基本信息表中的数据同步更新到部门库中*****************
				// 部门名称更新
				orgEntity.setName(baseInfoJson.getJSONObject("result").getString("name"));
				// 主管部门更新
				orgEntity.setParentId(baseInfoJson.getJSONObject("result").getString("compId"));
				// 机构类型更新
				orgEntity.setType(baseInfoJson.getJSONObject("result").getString("type"));
				// 所属系统更新
				orgEntity.setOwnSys(baseInfoJson.getJSONObject("result").getString("ownSys"));
				// 部门库表状态更新
				if(Contsants.OFS_UPDATE_TYPE_MERGE.equals(statusEntityInfo.getUpdateType())) {
					orgEntity.setStatus(Contsants.OFS_ORGANIZATION_FLAG_CANCEL);
				} else {
					orgEntity.setStatus(Contsants.OFS_ORGANIZATION_FLAG_NORMAL);
				}
				// 是否主管部门更新
				orgEntity.setIsComp(baseInfoJson.getJSONObject("result").getString("isComp"));
//				// 是否有下设部门更新
//				JSONObject orgInfoJsonResult =   organizationService.findChildOrgs(orgId);
//				// 注意result包了两层
//				JSONArray orgInfoJsonList =   orgInfoJsonResult.getJSONArray("result");
//				JSONObject orgInfoJsonObj = null;
//				String hasChild = Contsants.OFS_ORGANIZATION_FLAG_HAS_NO_CHILD;
//				for (int i=0; i < orgInfoJsonList.size(); i ++) {
//					orgInfoJsonObj = orgInfoJsonList.getJSONObject(i);
//					if(Contsants.OFS_ORGANIZATION_FLAG_NORMAL.equals(orgInfoJsonObj.getString("status")) ||
//							Contsants.OFS_ORGANIZATION_FLAG_CANCEL.equals(orgInfoJsonObj.getString("status"))) {
//						hasChild = Contsants.OFS_ORGANIZATION_FLAG_HAS_CHILD;
//						break;
//					}
//				}
				orgEntity.setHasChild(Contsants.OFS_ORGANIZATION_FLAG_HAS_NO_CHILD);
				// 设置更新时间
				orgEntity.setUpdateTime(new Date());
				// 设置更新用户ID
				 if(StringUtils.isNotEmpty(UserUtils.getCurrentUser().getId())) {
					 orgEntity.setUpdateUserId(Integer.valueOf(UserUtils.getCurrentUser().getId()));
		 		 }
				// TODO 以下字段暂不同步更新
				// 所属系统更新（areaID、areaCode、isSecret、local_code）
				// 部门编码和sort是创建的时点和赋码时点就固定了
				
			} else {
				// 部门库信息取得失败场合
				resultInfo.setCode(orgInfoJson.getString("code"));
				resultInfo.setMsg("[service.findById(organization)] in function of statusUpdate " + ResultPojo.MSG_FAILURE + "【"  + orgInfoJson.getString("msg") + "】" );
				resultInfo.setResult(null);
				return  resultInfo;
			}
			
			// 当变更的部门为主管部门时并且该部门的所属系统发生变更，
			// 此时递归更新该主管部门的下设机构的部门库信息和下设机构的部门基本信息的所属系统字段
			int ret =common.compOrgUpdateOwnSys(organizationService,organizationBaseService,orgEntity,resultInfo);
			if(ret != 0) {
				return resultInfo;
			}
			
			JSONObject  orgInfoJsonObj = (JSONObject)JSONObject.toJSON(orgEntity);
			// 根据ID更新部门库的编码信息
			JSONObject organizationInfoJson = organizationService.saveOrUpdate(orgInfoJsonObj);
			
			// 判断更新是否成功失败
			if (ResultPojo.CODE_SUCCESS.equals(organizationInfoJson.getString("code")) ) {
				// 保存成功场合
				resultInfo.setCode(ResultPojo.CODE_SUCCESS);
				resultInfo.setMsg(ResultPojo.MSG_SUCCESS);
				idMap.clear();
				idMap.put("id", organizationInfoJson.getJSONObject("result").getString("id"));
				idMap.put("baseId", organizationInfoJson.getJSONObject("result").getString("baseId"));
			} else {
				// 保存失败场合
				resultInfo.setCode(organizationInfoJson.getString("code"));
				resultInfo.setMsg("[service.update(organization)] in function of statusUpdate " + ResultPojo.MSG_FAILURE + "【"  + organizationInfoJson.getString("msg") + "】" );
				resultInfo.setResult(null);
				 // 程序事务控制
			  	 // 删除保存的部门审核意见信息 TODO
				return  resultInfo;
			}
			
			 //保存审核意见表
	    	 OrgOpinionsEntity opinionsEntityInfo = new OrgOpinionsEntity();
	    	 // 设置部门审核意见信息表baseId
	    	 opinionsEntityInfo.setBaseId(baseId.toString());
	    	 if(StringUtils.isNotEmpty(UserUtils.getCurrentUser().getId())) {
	    		 opinionsEntityInfo.setAuditUserId(Integer.valueOf(UserUtils.getCurrentUser().getId()));
	 		 }
	         
	         //******************第二步更新部门审核意见信息表**************************************
	         // 执行保存部门审核意见信息表
	    	 JSONObject opinionsInfoJson =  orgOpinionsService.saveOrUpdate(opinionsEntityInfo);
	    	 // 判断保存是否成功失败
	    	  if (ResultPojo.CODE_SUCCESS.equals(opinionsInfoJson.getString("code"))) {
	    		  // 保存成功场合
	    		  idMap.put("opinionsId", opinionsInfoJson.getJSONObject("result").getString("id"));
	    		  resultInfo.setResult(idMap);
	          } else {
	        	  // 保存失败场合
	        	  resultInfo.setCode(opinionsInfoJson.getString("code"));
	        	  resultInfo.setMsg("[orgOpinionsService.saveOrUpdate] in function of statusUpdate "
	        			  				+ ResultPojo.MSG_FAILURE  + "【"  + opinionsInfoJson.getString("msg") +"】");
	        	  resultInfo.setResult(null);
	         	  return resultInfo;
	          }
	    	 
		  }
         // 成功保存部门信息表和部门状态表返回
         return  resultInfo;
    }

}
